import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom'; // 引入 useNavigate 用于页面重定向
import './Login.css'; // Importing Login-specific styles
import { register } from '../api/userApi';  // 引入后端的注册接口

const Register = ({ onLogin }) => {
    const [account, setAccount] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState(''); // 新增的确认密码状态
    const [errorMessage, setErrorMessage] = useState('');
    const navigate = useNavigate();  // 页面重定向

    const handleSubmit = async (e) => {
        e.preventDefault();
        console.log('Registering with:', { account, password, confirmPassword });

        // 表单验证
        if (!account || !password || !confirmPassword) {
            setErrorMessage('请填写所有字段');
            return;
        }

        if (password !== confirmPassword) {
            setErrorMessage('密码和确认密码不一致');
            return;
        }

        try {
            console.log('调用注册接口');
            const result = await register(account, password);

            if (result.success) {
                const userId = result.data;
                console.log('注册成功:', result.data);
                // 自动登录
                if (typeof onLogin === 'function') {
                    onLogin(); // 执行父组件的登录逻辑
                }
                localStorage.setItem('userId', userId);
                navigate(`/home/${userId}`); // 跳转到主页，传递用户ID
            } else {
                // 处理注册失败的错误信息
                setErrorMessage(result.error || '注册失败，请稍后再试');
            }
        } catch (error) {
            console.error('注册过程中捕获错误:', error);
            setErrorMessage('注册失败，请稍后再试');
        }
    };

    // 跳转到登录页面
    const handleRegisterClick = () => {
        navigate('/');
    };

    return (
        <div className="login">
            <div className="login-container">
                <div className="login-form">
                    <h2>Orbitly</h2>
                    {/* 表单 */}
                    <div className='login-form-container'>
                        <form onSubmit={handleSubmit}>
                            {/* 用户名 */}
                            <div className="form-group">
                                <label htmlFor="account" className="form-label">用户名</label>
                                <input 
                                    type="text" 
                                    id="account" 
                                    value={account} 
                                    onChange={(e) => setAccount(e.target.value)} 
                                    className="form-input" 
                                    placeholder="请输入用户名"
                                    required
                                />
                            </div>

                            {/* 密码 */}
                            <div className="form-group">
                                <label htmlFor="password" className="form-label">密码</label>
                                <input 
                                    type="password" 
                                    id="password" 
                                    value={password} 
                                    onChange={(e) => setPassword(e.target.value)} 
                                    className="form-input" 
                                    placeholder="请输入密码"
                                    required
                                />
                            </div>

                            {/* 确认密码 */}
                            <div className="form-group">
                                <label htmlFor="confirmPassword" className="form-label">确认密码</label>
                                <input 
                                    type="password" 
                                    id="confirmPassword" 
                                    value={confirmPassword} 
                                    onChange={(e) => setConfirmPassword(e.target.value)} 
                                    className="form-input" 
                                    placeholder="请输入确认密码"
                                    required
                                />
                            </div>

                            {/* 提交按钮 */}
                            <button type="submit" className="form-submit-btn">注册</button>

                            {/* 错误信息 */}
                            {errorMessage && <p className="error-message">{errorMessage}</p>}

                            {/* 登录按钮 */}
                            <button type="button" class="register-btn" onClick={handleRegisterClick}>登录</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Register;